package com.jdn;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: arsentyev
 * Date: 21.08.12
 */
public class Parser {
    public static Container parse(String text, String name) {
        Container container = new Container();
        String s1 = null, s2 = null;

        Matcher matcher = Pattern.compile("/\\*\\*([\\S\\s]+?)\\*/([\\s\\S]+?)[\\{|;]").matcher(text), m2;

        Map<String, String> map = new HashMap<String, String>();
        while(matcher.find()) {
            s1 = checkString(matcher.group(2));
            s2 = matcher.group(1);
            if(s1.contains("class ") || s1.contains("interface ")) {
                container.setSyntax(s1.replaceAll("[a-z]+\\.", ""));
                container.setSummary(clearDesc(s2));

                m2 = Pattern.compile("@since\\s+([a-zA-Z0-9\\.]+)\\s*[\r\n]+").matcher(s2);

                if(m2.find()) {
                    container.setSince(m2.group(1));
                }

                m2 = Pattern.compile("@author\\s+([a-zA-Z\\.\\s]+)\\s*[\r\n]+").matcher(s2);

                while(m2.find()) {
                    container.addAuthor(m2.group(1));
                }
                continue;
            }
            map.put(s1, clearDesc(s2));
        }

        try {
            Reflect.fill(name, map, container);
        } catch (ClassNotFoundException e) {
            System.out.println(name + " not found.");
            return null;
        }

        return container;
    }

    private static String checkString(String s) {
        return moveBuf(delNames(delRNW(s)));
    }

    private static String delNames(String s) {
        return s.replaceAll("\\s[a-zA-Z]+(,|\\))", "$1").replace(", ", ",");
    }

    private static String delRNW(String s) {
        return s.replace("\r\n", "").replaceAll("\\s+", " ").trim();
    }

    private static String moveBuf(String s) {
        return s.replaceAll("([a-zA-Z\\[\\]]+)\\s[a-zA-Z]+\\[\\]", "$1[]");
    }

    private static String clearDesc(String s) {
        String[] tags = new String[] {"@see", "@version", "@since", "@param", "@author", "@serial", "@deprecated", "@exception", "@return", "@serialData", "@throws"};
        s = s.replaceAll("\\s\\*", "");
        int min = s.length(), i = 0;
        for(String ss: tags) {
            i = s.indexOf(ss);
            if (i > -1 && i < min) {
                min = i;
            }
        }

        return s.substring(0, min);
    }
}